package com.lishem.carl._07tree;

import com.lishem.common.TreeNode;

/**
 * https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
 * <p>
 * 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先
 */
public class _31LetCode235_二叉搜索树的最近公共祖先 {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root.val > p.val && root.val > q.val) {
            return lowestCommonAncestor(root.left, p, q);
        }
        if (root.val < p.val && root.val < q.val) {
            return lowestCommonAncestor(root.right, p, q);
        }
        return root;
    }

    public static void main(String[] args) {
        _31LetCode235_二叉搜索树的最近公共祖先 sol = new _31LetCode235_二叉搜索树的最近公共祖先();
        TreeNode root = new TreeNode(6);
        TreeNode p = new TreeNode(2);
        root.left = p;
        root.left.left = new TreeNode(0);
        root.left.right = new TreeNode(4);
        root.left.right.left = new TreeNode(3);
        root.left.right.right = new TreeNode(5);
        TreeNode q = new TreeNode(8);
        root.right = q;
        root.right.left = new TreeNode(7);
        root.right.right = new TreeNode(9);
        System.out.println(sol.lowestCommonAncestor(root, p, q).val);
    }
}
